import axios from 'axios';

const instance = axios.create({
  baseURL: '',
  timeout: 3000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
  withCredentials: true,
  xsrfCookieName: '',
});

const reqlock = {};

instance.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  function (response) {
    // 请求成功后解开请求锁
    let reqLockKey = null;
    if (response.config.method === 'get') {
      reqLockKey = response.config.params.reqLockKey;
    } else {
      if (response.config.method === 'post') {
        reqLockKey = JSON.parse(response.config.data).reqLockKey;
      }
    }
    if (reqLockKey) {
      reqlock[reqLockKey] = false;
    }
    return response.data;
  },
  function (error) {
    // 接口失败后解开所有请求锁
    for (const key in reqlock) {
      if (reqlock.hasOwnProperty(key)) {
        reqlock[key] = false;
      }
    }
    return Promise.reject(error);
  }
);

/**
 * @param {String} methods Request method: get、post、delete、put
 * @param {String} url Request url
 * @param {Object} data Request param
 * @returns {Promise}
 */
export default function (methods, url, data = null) {
  const method = methods.toLowerCase();

  // 有 reqLockKey 参数时，添加请求锁
  const { reqLockKey } = data;
  if (!reqLockKey || !reqlock[reqLockKey]) {
    reqLockKey && (reqlock[reqLockKey] = true);
  } else {
    return Promise.reject(null);
  }

  if (method === 'post') {
    const config = {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
      },
    };
    return instance.post(url, data, config);
  } else if (method === 'get') {
    return instance.get(url, {
      params: data,
    });
  } else if (method === 'delete') {
    return instance.delete(url, { data });
  } else if (method === 'put') {
    return instance.put(url, data);
  } else {
    return false;
  }
}
